"""
对话管理服务
处理多轮对话管理、情感识别和上下文维护
"""

from typing import Dict, Any, Optional, List
from datetime import datetime
import json
from src.utils.nlp_enhancement import get_nlp_support
from src.services.chatbot_service import ChatSession, chat_sessions, add_message_to_session
from src.utils.logging import get_logger

logger = get_logger(__name__)

class ConversationService:
    """对话管理服务类"""
    
    def __init__(self):
        self.nlp_support = get_nlp_support()
    
    def initialize_conversation_state(self, session: ChatSession) -> Dict[str, Any]:
        """
        初始化对话状态
        
        Args:
            session: 聊天会话对象
            
        Returns:
            初始化的对话状态
        """
        return {
            "turn_count": 0,
            "last_intent": None,
            "current_topic": None,
            "emotional_state": "neutral",
            "context_entities": {},
            "dialogue_acts": []
        }
    
    def update_conversation_state(self, session_id: str, user_message: str) -> Dict[str, Any]:
        """
        更新对话状态
        
        Args:
            session_id: 会话ID
            user_message: 用户消息
            
        Returns:
            更新后的对话状态
        """
        session = chat_sessions.get(session_id)
        if not session:
            return {}
        
        # 初始化对话状态
        if not getattr(session, 'conversation_state', None):
            session.conversation_state = self.initialize_conversation_state(session)
        
        # 更新轮次计数
        session.turn_count = getattr(session, 'turn_count', 0) + 1
        if session.conversation_state is not None:
            session.conversation_state["turn_count"] = session.turn_count
        
        # 情感分析
        sentiment_result = self.nlp_support.sentiment_analysis(user_message)
        if session.conversation_state is not None:
            session.conversation_state["emotional_state"] = sentiment_result["sentiment"]
        
        # 简单意图识别（可以扩展为更复杂的模型）
        if any(word in user_message for word in ["谢谢", "感谢", "thank"]):
            intent = "gratitude"
        elif any(word in user_message for word in ["再见", "拜拜", "bye", "see you"]):
            intent = "goodbye"
        elif any(word in user_message for word in ["什么", "怎么", "如何", "为什么", "what", "how", "why"]):
            intent = "question"
        else:
            intent = "statement"
        
        if session.conversation_state is not None:
            session.conversation_state["last_intent"] = intent
        
        # 更新话题（简单实现，可以扩展）
        if session.turn_count == 1:
            if session.conversation_state is not None:
                session.conversation_state["current_topic"] = user_message[:20] + "..." if len(user_message) > 20 else user_message
        
        # 每3轮更新一次对话摘要
        if session.turn_count % 3 == 0 and len(session.messages) > 3:
            session.conversation_summary = self.generate_conversation_summary(
                [msg for msg in session.messages if hasattr(msg, 'content')]
            )
        
        return session.conversation_state if session.conversation_state is not None else {}
    
    def generate_conversation_summary(self, messages: List[Any]) -> str:
        """
        生成对话摘要
        
        Args:
            messages: 消息列表
            
        Returns:
            对话摘要
        """
        if len(messages) <= 2:
            return ""
        
        # 只对前几条消息进行摘要
        summary_messages = messages[:min(6, len(messages))]  # 最多取前6条消息
        summary_prompt = f"""
        请为以下对话生成一个简短摘要（不超过3句话）：
        
        {chr(10).join([f"{getattr(m, 'type', 'unknown')}: {getattr(m, 'content', str(m))}" for m in summary_messages[-4:]])}
        
        摘要：
        """
        
        # 这里可以调用LLM生成摘要，简单实现直接返回前几条消息
        return "对话摘要: " + "; ".join([getattr(m, 'content', str(m))[:50] for m in summary_messages[-2:]])
    
    def generate_emotional_response(self, session: ChatSession, response_content: str) -> str:
        """
        根据情感状态调整响应
        
        Args:
            session: 聊天会话
            response_content: 原始响应内容
            
        Returns:
            调整后的情感化响应
        """
        conversation_state = getattr(session, 'conversation_state', None)
        emotional_state = "neutral"
        if conversation_state is not None:
            emotional_state = conversation_state.get("emotional_state", "neutral")
        
        # 根据用户情感状态调整响应
        if emotional_state == "negative":
            # 对负面情绪增加安慰语
            if not response_content.startswith(("很抱歉", "抱歉", "不好意思")):
                response_content = "很抱歉听到您的困扰。" + response_content
        elif emotional_state == "positive":
            # 对正面情绪增加积极回应
            last_intent = None
            if conversation_state is not None:
                last_intent = conversation_state.get("last_intent")
            if last_intent == "gratitude":
                response_content = "不客气！" + response_content
        
        return response_content

def get_conversation_service() -> ConversationService:
    """获取对话管理服务实例"""
    return ConversationService()